<?php
/**
 * Appleshell脚本逻辑
 */

namespace App\Datas;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Tools\GooglePay;
use App\Tools\FunTool;
use App\Tools\Af;
use App\Datas\Pay;
use App\Datas\User;
use App\Datas\UserDrawing;
use App\Datas\System;
use App\Datas\EventList;
use App\Datas\UserOntrial;
use LeeHom\AppleInAppPurchaseVerification;
use App\Tools\Tester;

class AppleShell
{


    /**
     * google 的未支付单
     */
    public static function checkAppleOrder(){

        $list = DB::table("pay_order")
                  ->where('platform', 1)//IOS支付的
                  ->where('client_notify', 1)
                  ->where('is_repair', 2)
                  ->whereNotNull('extend')
                  ->where('status',0)
                  ->limit(5)
                  ->get()->toArray();
        if (count($list) <=0) {
            echo '暂无数据要处理'.PHP_EOL;
            exit;
        }

        foreach ($list as $key => $value) {
            if ( !empty($value->external_order_id) || $value->status == 1 ) {//已经回调或者更改过来的
                Log::info('AppleShell-'.$value->order_id, ['状态已经更改，不操作此条数据']);
                continue;
            }
            if (empty($value->extend)) {//没有支付信息的
                Log::info('AppleShell-'.$value->order_id, ['支付信息 Extend 为空，不操作此条数据']);
                continue;
            }
            if ($value->google_is_subscribe == 1) {//订阅的
                self::dealAppleSubscribe($value->extend, $value->device_id, $value->id);
                
            }else{//正常购买商品的
                self::dealApplePurchase($value->extend, $value->device_id,  $value->id);
            }
        }

        echo '处理完毕'.PHP_EOL;
        exit;

    }


    /**
     * 处理 Apple 购买商品逻辑和后续业务处理
     */
    public static function dealApplePurchase($data, $deviceId, $payOrderId){

        $data = json_decode($data, true);

        $oTester = new Tester();
        $bSandbox = $oTester->isTester($deviceId);

        $appleIAP = new AppleInAppPurchaseVerification($data['receipt'], '46c5cf1c64084e5c81f3fe9d17a4be17', $bSandbox);
        $result = $appleIAP->validateReceipt();
        $result = json_decode($result, true);
        $orderData = $result['receipt']['in_app'][0] ?? null;
        if (!$orderData) {//不存在订单信息
            $remark = '补单流程：Apple接口未查询到订单信息，解析receipt错误';
            DB::table('pay_order')->where('id',$payOrderId)->update(['remark'=>$remark,'is_repair'=>1]);
            return false ;
        }
        if ($result['receipt']['bundle_id'] != 'FA.FaceAppAI' ) {
            $remark = '补单流程：bundle_id不是 FA.FaceAppAI，而是'.$result['receipt']['bundle_id'];
            DB::table('pay_order')->where('id',$payOrderId)->update(['remark'=>$remark, 'is_repair'=>1]);
            return false;
        }

        $externalOrderId = $orderData['transaction_id'];
        $externalOrder = (new Pay())->getOrderWithExternalOrderId($externalOrderId);
        if ($externalOrder) {
            $remark = '补单流程：订单号已经存在，不继续处理';
            DB::table('pay_order')->where('id',$payOrderId)->update(['remark'=>$remark,'is_repair'=>1]);
            return false;
        }

        $res = self::doBusiness($payOrderId, $orderData, false);
        $dataPay = new Pay();
        if ($res['code'] == 200) {
            $dataPay->updatePayById($payOrderId, ['remark'=>$res['msg'],'is_repair'=>1, 'status'=>1,'pay_at'=>FunTool::getReduceTime(4)]);
        }else{
            $dataPay->updatePayById($payOrderId, ['remark'=>$res['msg'],'is_repair'=>1]);
        }
        
        Log::info('ApplePurchaseShell-'.$data['order_id'], [$res]);

    }

    /**
     * 处理订阅消息
     */
    public static function dealAppleSubscribe($data, $deviceId, $payOrderId){

        $data = json_decode($data, true);

        $oTester = new Tester();
        $bSandbox = $oTester->isTester($deviceId);

        $appleIAP = new AppleInAppPurchaseVerification($data['receipt'], '46c5cf1c64084e5c81f3fe9d17a4be17' , $bSandbox);
        $result = $appleIAP->validateReceipt();

        if (!$result) {
            $remark = '补单流程：Apple接口未查询到订单信息，解析receipt错误';
            DB::table('pay_order')->where('id',$payOrderId)->update(['remark'=>$remark,'status'=>3,'is_repair'=>1]);
            return false ;
        }
        $result = json_decode($result, true);
        if (!isset($result['latest_receipt_info'])) {
            $remark = '补单流程：不存在 latest_receipt_info';
            DB::table('pay_order')->where('id',$payOrderId)->update(['remark'=>$remark,'status'=>3,'is_repair'=>1]);
            return false ;
        }
        $latestReceiptList = $result["latest_receipt_info"];
        array_multisort(array_column($latestReceiptList, 'purchase_date_ms'), SORT_DESC, $latestReceiptList);
        $last = $latestReceiptList[0];
    
        //本次交易流水号
        $transaction_id = $last["transaction_id"];
        //原始订单号
        $original_transaction_id = $last["original_transaction_id"];

        $dataPay = new Pay();

        $num = $dataPay->getNumByAppleTrade([
            "external_order_id" => $transaction_id,
            "transaction_order_id" => $original_transaction_id,
        ]);
        if ($num > 0) {
            //防止重复订阅
            $remark = '补单流程：已经订阅过';
            DB::table('pay_order')->where('id',$payOrderId)->update(['remark'=>$remark,'is_repair'=>1]);
            return false ;
        }
        $res = $this->doBusiness($payOrderId, $last, true);

        $dataPay = new Pay();
        if ($res['code'] == 200) {
            $dataPay->updatePayById($payOrderId, ['remark'=>$res['msg'],'is_repair'=>1, 'status'=>1]);
        }else{
            $dataPay->updatePayById($payOrderId, ['remark'=>$res['msg'],'is_repair'=>1]);
        }
        Log::info('AppleSubscribeShell-'.$data['order_id'], [$res]);


    }

    
    /**
     * 处理 Apple 购买逻辑和后续业务处理
     */
    public static function doBusiness($payOrderId, $orderData, $subscribe = false) {

        $dataPay = new Pay();

        $orderInfo = $dataPay->getFirstInfo(['id'=>$payOrderId]);

        $remark = $orderInfo['remark'];

        if ($orderInfo['status'] != 0  || !empty($orderInfo['external_order_id'])) {
            $remark.= ' 补单流程：支付状态和数据已更改，停止进行...';
            return ['code'=>500, 'msg'=>'补单流程：支付状态和数据已更改，停止进行...'];
        }
        $isSuperVip = false;
        $externalOrderId = $orderData['transaction_id'];

        if ($orderData['in_app_ownership_type'] != 'PURCHASED') {//不是支付成功的
            $remark.= ' 补单流程：支付失败，状态为：'.$orderData['in_app_ownership_type'];
            $dataPay->updatePayById($payOrderId, ['status'=>2]);
            return ['code'=>500, 'msg'=>' 补单流程：支付失败，状态为：'.$orderData['in_app_ownership_type']];
        }

        DB::beginTransaction();
        try {
            $id = $orderInfo['id'];
            if ($orderData['quantity'] > 1) {
                $orderInfo["price"] = $orderInfo["price"] * $orderData['quantity'];
                $orderInfo["dot"] = $orderInfo["dot"] * $orderData['quantity'];
                $dataPay->updatePayById($id,[
                    "price" => $orderInfo["price"],
                    "dot" => $orderInfo["dot"]
                ]);
            }
            $dataPay->updatePay($id, $externalOrderId);

            $userDrawing = new UserDrawing();
            $dataUser = new User();
            //兼容无登录付费
            if($orderInfo['dot'] > 0 && $orderInfo['user_id'] > 0) {
                $dataUser->updateDot($orderInfo['user_id'], $orderInfo['dot'], 4);
            }
            if (version_compare($orderInfo['version'],  env('NEW_VERSION')) >= 0) {
                //兼容无登录付费
                if($orderInfo['len'] > 0 && $orderInfo['len'] != 36500 && $orderInfo["user_id"] > 0) {
                    if ($orderInfo['is_gold'] == 1) {
                        //续费黄金会员的时间
                        $dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['len'] * 24 * 3600, 'vip_exp');
                    } else {
                        //续费普通画板的时间
                        $userDrawing->updateUserDrawExp($orderInfo['user_id'], $orderInfo['drawing_id'], $orderInfo['len'] * 24 * 3600);
                    }
                }
            } else {
                if($orderInfo['len'] > 0) {
                    $dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['len']*24*3600, 'vip_exp');
                }
                if($orderInfo['ecy_len'] > 0) {
                    $dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['ecy_len']*24*3600, 'rcy_vip_exp');
                }
            }

            // 更新终生会员
            $isSuperVip = $orderInfo["google_id"] == "lifetime_pro" ? true : false;// 是否是终生会员
            if ($isSuperVip && $orderInfo["user_id"] > 0) {
                $dataUser->updateById($orderInfo['user_id'],["is_super_vip" => 1]);
            }
            //兼容无登录付费
            if ($orderInfo['dot'] > 0 && $orderInfo['user_id'] > 0) {
                //设置充值赠送点数动画值
                $dataUser->setDhNum($orderInfo['user_id'], $orderInfo['dot']);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return ['code'=>500, 'msg'=>json_encode(["error" => $e->getMessage(),"line" => $e->getLine()])];
        }
        $guid = $orderInfo['device_id'];
        if (empty($guid)) {
            $remark.= ' 补单流程：device_id为空，不进行上报AF...';
            return ['code'=>500, 'msg'=>'device_id为空，不进行上报AF'];
        }
        $systemData = new System();
        $deviceInfo = $systemData->getDevice($guid);
        /*上报订阅数据到AF 开始*/
        $appid = FunTool::getAfAppidByPf($orderInfo['platform']);
        $af = new Af();

        if ($subscribe) {//订阅的

            $_aExt = ['line'=>__LINE__, 'in' => 'isAppleCheckPayBusiness', 'order' => $orderInfo, 'appleSubscribe' => true];
            $af->subscribeEvent($deviceInfo['appsfly_id'],$appid,$_aExt);
            EventList::getInstance()->subscribePayEvent($orderInfo["platform"],$orderInfo["version"],$orderInfo["device_id"],"subscribe_suc");

            $_aExt = ['line'=>__LINE__, 'in' => 'doPay', 'order' => $orderInfo, 'externalOrderId' => $externalOrderId];
            $af->payEvent($deviceInfo['appsfly_id'],$appid,$orderInfo['price'], $_aExt);
            
        }else{
            $_aExt = ['line'=>__LINE__, 'in' => 'isAppleCheckPayBusiness', 'order' => $orderInfo, 'externalOrderId' => $externalOrderId];
            $af->payEvent($deviceInfo['appsfly_id'],$appid,$orderInfo['price'], $_aExt);
            //@todo eks 购买终身会员事件上报
            if(true === $isSuperVip){
                EventList::getInstance()->subscribePayEvent($orderInfo["platform"],$orderInfo["version"],$orderInfo["device_id"],"subscribe_suc");
            }
        }
        
        /*上报订阅数据到AF 结束*/

        return ['code'=>200, 'msg'=>'成功'];
    }

    

    


    
}